import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:qr_flutter/qr_flutter.dart';
import 'package:ws_group_chat/provider/host_data.dart';

class HostChatPage extends StatefulWidget {
  const HostChatPage({super.key});

  @override
  State<HostChatPage> createState() => _HostChatPageState();
}

class _HostChatPageState extends State<HostChatPage> {
  final TextEditingController _messageController = TextEditingController();
  final ScrollController _scrollController = ScrollController();
  late final HostData _hostData;
  @override
  void initState() {
    super.initState();
    _hostData = context.read<HostData>();
  }

  @override
  void dispose() {
    _hostData.close();
    super.dispose();
  }

  void _sendMessage() {
    _hostData.sendMessage(_messageController.text);
    _messageController.clear();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('聊天室(${context.watch<HostData>().playersCount})'),
        backgroundColor: Colors.transparent,
        actions: [
          IconButton(
            onPressed: () {
              // 点击生成一个二维码弹窗，给中途加入的玩家扫码加入
              showDialog(
                context: context,
                builder: (context) => AlertDialog(
                  title: const Text('扫码加入'),
                  content: SizedBox(
                    width: 200.0,
                    height: 200.0,
                    child: QrImageView(
                      data: _hostData.wsUrl!,
                      version: QrVersions.auto,
                      size: 200.0,
                    ),
                  ),
                ),
              );
            },
            icon: const Icon(Icons.qr_code),
          ),
        ],
      ),
      body: Column(
        children: [
          Expanded(
            child: Consumer<HostData>(
              builder: (context, vm, child) {
                // 自动滚动到底部
                WidgetsBinding.instance.addPostFrameCallback((_) {
                  if (_scrollController.hasClients) {
                    _scrollController.jumpTo(
                      _scrollController.position.maxScrollExtent,
                    );
                  }
                });
                return ListView.builder(
                  itemBuilder: (context, index) {
                    bool isMe = vm.chatMessages[index].userName == vm.userName;
                    if (isMe) {
                      return Row(
                        mainAxisAlignment: isMe
                            ? MainAxisAlignment.end
                            : MainAxisAlignment.start,
                        children: [
                          Text(
                            "${vm.chatMessages[index].msg} ${vm.chatMessages[index].userName}",
                          ),
                        ],
                      );
                    } else {
                      return Row(
                        mainAxisAlignment: isMe
                            ? MainAxisAlignment.end
                            : MainAxisAlignment.start,
                        children: [
                          Text(
                            "${vm.chatMessages[index].userName} ${vm.chatMessages[index].msg}",
                          ),
                        ],
                      );
                    }
                  },
                  itemCount: vm.chatMessages.length,
                );
              },
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(16.0),
            child: Row(
              children: [
                Expanded(child: TextField(controller: _messageController)),
                const SizedBox(width: 8),
                IconButton(
                  onPressed: _sendMessage,
                  icon: const Icon(Icons.send),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
